package net.tarine.gastronomi.client;

import net.tarine.gastronomi.client.forms.ForumThreadPage;
import net.tarine.gastronomi.client.forms.ForumThreadListPage;
import net.tarine.gastronomi.client.forms.GasEditPage;
import net.tarine.gastronomi.client.forms.GasUserListPage;

import com.google.gwt.user.client.ui.SimplePanel;

public class HistoryMgr {
	
	public static final String SEPARATOR_TOKEN = "_";
	public static final String SEPARATOR_PARAMS = "/";
	public static final String SEPARATOR_VALUES = "=";
	
	public static final String PARAM_ID = "id";
	
	public static final String INDEX = "index";
	public static final String GAS_EDIT = "gasEdit";
	public static final String GAS_USER_FIND = "gasUserFind";
	public static final String FORUM_THREAD_FIND = "forumThreadFind";
	public static final String FORUM_THREAD_EDIT = "forumThreadEdit";
	//public static final String FORUM_MSG_EDIT = "forumMessageEdit";
	
	public static void loadContent(String fullToken) {
		if (fullToken != null) {
			String token = tokenFromUri(fullToken);
			ParamMap params = paramsFromUri(fullToken);
			SimplePanel contentPanel = UiSingleton.get().getContentPanel();
			contentPanel.clear();
			if (INDEX.equals(token)) {
				contentPanel.add(new ForumThreadListPage());
			}
			if (GAS_EDIT.equals(token)) {
				contentPanel.add(new GasEditPage(params));
			}
			if (GAS_USER_FIND.equals(token)) {
				contentPanel.add(new GasUserListPage(params));
			}
			if (FORUM_THREAD_FIND.equals(token)) {
				contentPanel.add(new ForumThreadListPage());
			}
			if (FORUM_THREAD_EDIT.equals(token)) {
				contentPanel.add(new ForumThreadPage(params));
			}
		}
	}
	
	private static String tokenFromUri(String fullToken) {
		String result = null;
		String[] pieces = fullToken.split(SEPARATOR_TOKEN);
		if (pieces.length >= 1) {
			result = pieces[0];
		}
		return result;
	}
	
	private static ParamMap paramsFromUri(String fullToken) {
		//Extract only the part after SEPARATOR_TOKEN
		String parameters = null;
		String[] tokenPieces = fullToken.split(SEPARATOR_TOKEN);
		if (tokenPieces.length >= 2) {
			parameters = tokenPieces[1];
		} else {
			return null;
		}
		
		//Extract parameters and put them in a map
		ParamMap result = new ParamMap();
		String[] pieces = parameters.split(SEPARATOR_PARAMS);
		if (pieces.length >= 1) {
			for (String piece : pieces) {
				String[] couple = piece.split(SEPARATOR_VALUES);
				if (couple.length >= 2) {
					result.addParam(couple[0], couple[1]);
				}
			}
		}
		return result;
	}
}
